<template>
  <div
    :class="[
      'message-input-toolbar',
      !isPC && 'message-input-toolbar-h5',
      isUniFrameWork && 'message-input-toolbar-uni',
    ]"
  >
    <div
      :class="[
        'message-input-toolbar-list',
        !isPC && 'message-input-toolbar-h5-list',
        isUniFrameWork && 'message-input-toolbar-uni-list',
      ]"
    >
      <EmojiPicker
        v-if="!isUniFrameWork"
        @insertEmoji="insertEmoji"
        @dialogShowInH5="dialogShowInH5"
        @dialogCloseInH5="dialogCloseInH5"
      ></EmojiPicker>
	  
	  <div @click="openAuth2('CAMERA')">
		  <ImageUpload  v-if="isUniFrameWork" imageSourceType="camera"></ImageUpload>
	  </div>
	  
	  <div style="position:relative">
			<!-- <div class="mask" v-if="xiangce_permission<1"  @click="openAuth()"></div> -->
			<ImageUpload imageSourceType="album"></ImageUpload>
	  </div>
	  
	  <div @click="openAuth()" v-if="!isUniFrameWork">
		<FileUpload  v-if="!isUniFrameWork"></FileUpload>
	  </div>
	  
	  <div @click="openAuth()">
		<VideoUpload  videoSourceType="album"></VideoUpload>
	  </div>
	  
	  <div @click="openAuth2('CAMERA')" v-if="isUniFrameWork" >
		<VideoUpload  v-if="isUniFrameWork" videoSourceType="camera"></VideoUpload>
	  </div>
	  
      <Evaluate></Evaluate>
      <Words></Words>
      <template v-if="extensionListShowInStart&&extensionListShowInStart[0]">
        <ToolbarItemContainer v-if="is_voice_call==1"
          v-for="(extension,ind) in extensionListShowInStart" :key="ind"
          :iconFile="genExtensionIcon(extension)"
          :title="genExtensionText(extension)"
          :iconWidth="isUniFrameWork ? '25px' : '20px'"
          :iconHeight="isUniFrameWork ? '25px' : '20px'"
          :needDialog="false"
          @onIconClick="onExtensionClick(extension)"
        />
      </template>
    </div>
    <div v-if="extensionListShowInEnd&&extensionListShowInEnd[0] && isPC" :class="['message-input-toolbar-list-end']">
      <ToolbarItemContainer
        v-for="(extension,index) in extensionListShowInEnd" :key="index"
        :iconFile="genExtensionIcon(extension)"
        :title="genExtensionText(extension)"
        :iconWidth="isUniFrameWork ? '25px' : '20px'"
        :iconHeight="isUniFrameWork ? '25px' : '20px'"
        :needDialog="false"
        @onIconClick="onExtensionClick(extension)"
      />
    </div>
    <UserSelector
      ref="userSelectorRef"
      :type="selectorShowType"
      :currentConversation="currentConversation"
      :isGroup="isGroup"
      @submit="onUserSelectorSubmit"
      @cancel="onUserSelectorCancel"
    />
    <div v-if="isH5" :class="['message-input-toolbar-h5-dialog']" ref="h5Dialog"></div>
	
	<!-- <yk-authpup ref="authpup" type="top" @changeAuth="changeAuth" :permissionID="permissionID"></yk-authpup>
	<yk-authpup ref="authpup2" type="top" @changeAuth="changeAuth2" :permissionID="permissionID2"></yk-authpup> -->
	
	
  </div>
</template>



<script setup lang="ts">	
import ykAuthpup from "@/components/yk-authpup/yk-authpup";
import { ref, computed, onUnmounted } from "../../../adapter-vue";
import TUIChatEngine, {
  IConversationModel,
  TUIStore,
  StoreName,
} from "@tencentcloud/chat-uikit-engine";
import TUICore, { ExtensionInfo, TUIConstants } from "@tencentcloud/tui-core";
import EmojiPicker from "./emoji-picker/index.vue";
import ImageUpload from "./image-upload/index.vue";
import FileUpload from "./file-upload/index.vue";
import VideoUpload from "./video-upload/index.vue";
import Evaluate from "./evaluate/index.vue";
import Words from "./words/index.vue";
import ToolbarItemContainer from "./toolbar-item-container/index.vue";
import UserSelector from "./user-selector/index.vue";
import { Toast, TOAST_TYPE } from "../../common/Toast/index";
import { isPC, isH5, isApp, isUniFrameWork } from "../../../utils/env";
import TUIChatConfig from "../config";
import { enableSampleTaskStatus } from "../../../utils/enableSampleTaskStatus";
import { Ref } from "@vue/runtime-dom";
import {
		HTTP_REQUEST_URL,
		PERFIX,
		kfs,
		IM_SDKAppID
	} from '@/config/app';
const emits = defineEmits(["insertEmoji"]);
const h5Dialog = ref();
const currentConversation = ref<IConversationModel>();
const isGroup = ref<boolean>(false);
const selectorShowType = ref<string>("");
const userSelectorRef = ref();
const currentUserSelectorExtension = ref<ExtensionInfo>();
const currentExtensionList = ref<ExtensionInfo>([]);

const systemInfo = uni.getSystemInfoSync();
const platform = systemInfo.platform;
const xiangce_permission =ref(-1)

const checkPermissins=()=>{
	if (platform != 'ios') {
		const permissions_array = ['android.permission.WRITE_EXTERNAL_STORAGE','android.permission.READ_EXTERNAL_STORAGE']
		const mainActivity = plus.android.runtimeMainActivity();
		const PackageManager = plus.android.importClass('android.content.pm.PackageManager');
		permissions_array.forEach(str => {
			const hasPermission = mainActivity.checkSelfPermission(str) === PackageManager.PERMISSION_GRANTED;
			if (!hasPermission) {
				console.log(`相册 权限未开启`);
				uni.setStorageSync('xiangce_permission', 0);
				xiangce_permission.value=0
				//this.promptToOpenSettings(); // 引导用户前往设置
			} else {
				console.log(`相册 权限已开启`);
				xiangce_permission.value=1
				uni.setStorageSync('xiangce_permission', 1);
			}
		});
	}else{
		xiangce_permission.value=1
		uni.setStorageSync('xiangce_permission', 1);
	}
}
checkPermissins()

const permisesions = [{
						key: "WRITE_EXTERNAL_STORAGE",
						value: false
					}
					// ,{
					// 	key: "READ_EXTERNAL_STORAGE",
					// 	value: false,
					// },
					];

const authpup:Ref = ref("");
const authpup2:Ref = ref("");

let permissionID = ref();
let permissionID2 = ref('CAMERA');

const openAuth = () => {
	//这个是对应的权限 ACCESS_FINE_LOCATION 位置权限 / READ_EXTERNAL_STORAGE WRITE_EXTERNAL_STORAGE 存储空间/照片权限 / CAMERA相机权限 / CALL_PHONE 拨打电话	
	//permissionID.value = ID
	//authpup.value.open();
	
	// App.vue里面用新的组件啦
	// if (platform != 'ios') {
	// 	const not = permisesions.find(item => item.value === false);
	// 	if(not){
	// 		permissionID.value = not.key;
	// 		setTimeout(() => {
	// 			authpup.value.open();
	// 		},500)
	// 	}
	// }
};
		
const openAuth2 = (ID:string) => {
	//这个是对应的权限 ACCESS_FINE_LOCATION 位置权限 / READ_EXTERNAL_STORAGE 存储空间/照片权限 / CAMERA相机权限 / CALL_PHONE 拨打电话	
	
	// App.vue里面用新的组件啦
	//permissionID2.value = ID
	//authpup2.value.open();
	
};		

//用户授权权限后的回调
const changeAuth = () =>{
	let currentPermission = permisesions.find(item => item.key === permissionID.value);
	if(currentPermission){
		currentPermission.value = true
		//这里是权限通过后执行自己的代码逻辑
		console.log('权限已授权，可执行自己的代码逻辑了');
		openAuth()
	}
	checkPermissins()
}

const changeAuth2 = () =>{
	//这里是权限通过后执行自己的代码逻辑
	console.log('权限已授权，可执行自己的代码逻辑了');
}

const getExtensionList = (conversationID:string) => {
  if (!conversationID) {
    return currentExtensionList.value = extensionList;
  }
  const chatType = TUIChatConfig.getChatType();
  const options:any = {
    chatType,
  }
  // 向下兼容，callkit 没有chatType 判断时，使用 filterVoice、filterVideo 过滤
  if (chatType === "customerService") {
    options.filterVoice = true;
    options.filterVideo = true;
    enableSampleTaskStatus("customerService");
  }
  currentExtensionList.value = [
    ...TUICore.getExtensionList(TUIConstants.TUIChat.EXTENSION.INPUT_MORE.EXT_ID, options),
  ];
}


let is_voice_call = ref(0)
if(uni.getStorageSync('userInfoFull')){
	is_voice_call = uni.getStorageSync('userInfoFull').user.is_voice_call
	console.log(is_voice_call)
}

const onCurrentConversationUpdate = (conversation: IConversationModel) => {
  if (conversation?.conversationID && currentConversation.value?.conversationID !== conversation?.conversationID) {
      getExtensionList(conversation?.conversationID);
    }
    currentConversation.value = conversation;
    if (currentConversation?.value?.type === TUIChatEngine.TYPES.CONV_GROUP) {
      isGroup.value = true;
    } else {
      isGroup.value = false;
    }
}

TUIStore.watch(StoreName.CONV, {
  currentConversation: onCurrentConversationUpdate,
});

onUnmounted(() => {
  TUIStore.unwatch(StoreName.CONV, {
    currentConversation: onCurrentConversationUpdate,
  });
});

// extensions
const extensionList: Array<ExtensionInfo> = [
  ...TUICore.getExtensionList(TUIConstants.TUIChat.EXTENSION.INPUT_MORE.EXT_ID),
];

// 按展示位置分类 extensionList （注意：仅 web 端 区分展示位置在 从 start 开始和 从 end 开始，在移动端不生效）
let extensionListShowInStart_native = computed(
  (): Array<ExtensionInfo> =>
    isPC ? currentExtensionList.value.filter((extension: ExtensionInfo) => extension?.data?.name !== "search") : currentExtensionList.value
);
let extensionListShowInStart = ref([])

extensionListShowInStart_native.value.forEach(nitem=>{
	if(!extensionListShowInStart.value.find(item=>item.text==nitem.text)){
		extensionListShowInStart.value.push(nitem)
	}
})
 
 console.log(extensionListShowInStart)

const extensionListShowInEnd = computed(
  (): Array<ExtensionInfo> =>
    isPC ? [currentExtensionList.value.find((extension: ExtensionInfo) => extension?.data?.name === "search")] : []
);


// handle extensions onclick
const onExtensionClick = (extension: ExtensionInfo) => {
  switch (extension?.data?.name) {
    case "voiceCall":
      onCallExtensionClicked(extension, 1);
	  operateLiuyan(1)
      break;
    case "videoCall":
      onCallExtensionClicked(extension, 2);
	  operateLiuyan(2)
      break;
    case "search":
      extension?.listener?.onClicked();
      break;
    default:
      break;
  }
};


const operateLiuyan = (type:Number) =>{
	var id = uni.getStorageSync('customer_message_board_id')
	console.log({id:id,user_id:uni.getStorageSync('user_id'),operate_type:type})
	uni.request({
		url: HTTP_REQUEST_URL + '/basic/operateLiuyan',
		data:{id:id,user_id:uni.getStorageSync('user_id'),operate_type:type},
		success: (r) => {
			console.log(r)
		}
	})
};


const onCallExtensionClicked = (extension: ExtensionInfo, callType: number) => {
  selectorShowType.value = extension?.data?.name;
  if (currentConversation?.value?.type === TUIChatEngine.TYPES.CONV_C2C) {
    extension?.listener?.onClicked({
      userIDList: [currentConversation?.value?.conversationID?.slice(3)],
      type: callType,
    });
  } else if (isGroup.value) {
    currentUserSelectorExtension.value = extension;
    userSelectorRef?.value?.toggleShow && userSelectorRef.value.toggleShow(true);
  }
};

const genExtensionIcon = (extension: any) => {
  return extension?.icon;
};
const genExtensionText = (extension: any) => {
  return extension?.text;
};

const onUserSelectorSubmit = (selectedInfo: any) => {
  currentUserSelectorExtension.value?.listener?.onClicked(selectedInfo);
  currentUserSelectorExtension.value = null;
};

const onUserSelectorCancel = () => {
  currentUserSelectorExtension.value = null;
};

const insertEmoji = (emojiObj: object) => {
  emits("insertEmoji", emojiObj);
};

const dialogShowInH5 = (dialogDom: any) => {
  if (!isH5) {
    return;
  }
  h5Dialog?.value?.appendChild && h5Dialog?.value?.appendChild(dialogDom);
};

const dialogCloseInH5 = (dialogDom: any) => {
  if (!isH5) {
    return;
  }
  h5Dialog?.value?.removeChild && h5Dialog?.value?.removeChild(dialogDom);
};
</script>
<style lang="scss" scoped>
@import "../../../assets/styles/common.scss";
.message-input-toolbar {
  border-top: 1px solid #f4f5f9;
  width: 100%;
  max-width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  &-list {
    display: flex;
    flex-direction: row;
    align-items: center;
    .extension-list {
      list-style: none;
      display: flex;
      &-item {
        width: 20px;
        height: 20px;
        padding: 12px 10px 1px;
        cursor: pointer;
      }
    }
  }
}
.message-input-toolbar-h5 {
  padding: 5px 10px 5px;
  box-sizing: border-box;
  flex-direction: column;
}

.message-input-toolbar-uni {
  background-color: #ebf0f6;
  flex-direction: column;
  &-list {
    flex: 1;
    display: grid;
    grid-template-columns: repeat(4, 25%);
    grid-template-rows: repeat(2, 100px);
  }
}
.mask{
	position: absolute;
	width: 100%;
	height: 100%;
	background-color: #3c3;
	z-index: 9;
}
</style>
